///////////////////////////
//本地存储
//////////////////////////
import { ImageAsset, assetManager, SpriteFrame, Node, sys, Sprite, Label } from 'cc';
import { Http, RoomConfig } from './Net';
import { Util } from './Util';
import { Wechat } from '../Market/Wechat';
import { GoldAmple } from './Type';
/**common数据存储类 */
enum UserType {
  Gamer = 'gamer',//玩家信息
  Game = 'game',//游戏场景配置
  RoomInfo = 'roominfo',//套接字房间id信息
  RoomList = 'roomlist',//房间配置列表
  RoomConfig = 'roomConfig',//单独房间配置
  AudioConfig = 'audioConfig',//音乐配置
  Fund = 'fund'
}

class StorageInfo {
  private storage: Storage = sys.localStorage;
  private key: UserType;
  constructor(key: UserType) {
    this.key = key;
  }
  /**拿data */
  protected getData<T>() {
    const data = this.storage.getItem(this.key);
    if (String(data).length > 2) {
      return JSON.parse(data) as T;
    } else {
      return undefined;
    }
  }
  /**存data */
  saveData<T>(data: T) {
    this.storage.removeItem(this.key);//清空前面的数据
    this.storage.setItem(this.key, JSON.stringify(data));
  }
  /**清空指定数据 */
  clearData(type: UserType) {
    this.storage.removeItem(type);
  }
}
/**金币钻石节点传过来设值 */
export class Fund extends StorageInfo {
  constructor(cion: Label, diamond: Label) {
    super(UserType.Fund)
    new Http<QueryUserInfo>(suc => {
      if (suc.code === 0) {
        const data = new Gamer().data;
        data.data.user.coin = suc.data.coin;//跟新金币
        data.data.user.diamond = suc.data.diamond;//更新钻石
        new Gamer().saveData(data);
        try {
          cion.string = new Util.Format(suc.data.coin).toString()
          diamond.string = new Util.Format(suc.data.diamond).toString()
        } catch (error) {
          // console.log('节点错误');
        }
      }
    }).gamerinfo({
      source: 'client',
      uid: String(new Gamer().uid)
    })
  }
}
/**玩家登录数据类 */
export class Gamer extends StorageInfo {
  constructor() {
    super(UserType.Gamer);
  }
  /**本地是否有数据并且没过期 */
  isData(callfun: (bol: boolean) => void) {
    if (this.getData() !== undefined) {//判断是否已经存有数据
      new Http<RoomConfig>(suc => {
        let bol: boolean = true;
        if (suc.code !== 0) bol = false;
        console.log(suc);
        callfun(bol);
      }).roolist();
    } else {
      callfun(false);
    }
  }
  /**设置传入node节点的对应头头像和名字*/
  setInfo(iconNode: Node, nameNode: Node, idNode?: Node) {
    iconNode && (assetManager.loadRemote<ImageAsset>(this.data.data.user.avatar, { ext: ".jpg" }, (err, img_data) => {
      if (!err) {
        iconNode.getComponent(Sprite).spriteFrame = SpriteFrame.createWithImage(img_data)
      } else {
        console.log("图片资源加载失败");
      }
      // console.log("头像数据", img_data);
    }));
    // iconNode && (assetManager.loadRemote<ImageAsset>(this.data.data.user.avatar, { ext: ".jpg" }, (err, img_data) => {
    //   if (!err) iconNode.getComponent(Sprite).spriteFrame = SpriteFrame.createWithImage(img_data);
    //   // console.log("头像数据", img_data);
    // }));
    nameNode && (nameNode.getComponent(Label).string = `${this.name}`);
    idNode && (idNode.getComponent(Label).string = `ID:${this.uid.toString()}`);
  }
  /**清空数据 */
  clear() {
    this.clearData(UserType.Gamer);
  }
  /**获取token*/
  get token() {
    let data = this.getData<GamerInfoType>();
    if (data !== undefined) {
      return data.data.token;
    } else {
      console.log('data没找到');
      new Wechat().exit();
      return '';
    }
  }
  get data() {
    return this.getData<GamerInfoType>();
  }
  get uid() {
    try {
      return this.getData<GamerInfoType>().data.user.uid;
    } catch (error) {
      console.log('data.user.uid为null');
    }
  }
  get name() {
    return this.getData<GamerInfoType>().data.user.nickname;
  }
  get coin() {
    return this.getData<GamerInfoType>().data.user.coin;
  }
  get diamond() {
    return this.getData<GamerInfoType>().data.user.diamond;
  }
}
/**游戏内配置设置 */
export class GameID extends StorageInfo {
  constructor() {
    super(UserType.Game);
  }
  get uid() {
    const uid = this.getData<GameRoomConfig>().uid;
    return uid;
  }
  get roomid() {
    const roomid = this.getData<GameRoomConfig>().roomid;
    return roomid;
  }
  get scroe() {
    const score = this.getData<GameRoomConfig>().score;
    return score;
  }
  get base_score() {
    const base_score = this.getData<GameRoomConfig>().base_score;
    return base_score;
  }
  get roomtitle() {
    const name = this.getData<GameRoomConfig>().roomtitle;
    return name;
  }
}
/**套接字房间id */
export class RoomInfo extends StorageInfo {
  constructor() {
    super(UserType.RoomInfo)
  }
  setID(roomid: number, type: number) {
    this.saveData({ roomid, type });
  }
  get id(): number {
    return this.getData<{ roomid: number, type: number }>().roomid;
  }
  get type(): number {
    return this.getData<{ roomid: number, type: number }>().type;
  }
}


export enum RoomType {
  classic = 1,
}
/**房间配置类 */
export class RoomList extends StorageInfo {
  constructor() {
    super(UserType.RoomList);
  }
  /**拿取指定name的room配置 */
  getRoomConfig(room_type: RoomType) {
    const roomlist = this.getData<RoomConfig>().data;
    const roomconfig = roomlist.filter(room => room.game_type === room_type)[0];
    // console.log("原始数据", roomlist);
    // console.log("过滤后的数据", roomconfig);
    return roomconfig;
  }
}

/**音乐配置 */
export class AudioConfig extends StorageInfo {
  constructor() {
    super(UserType.AudioConfig);
  }
  init(config: AudioConfig_ = { soundEffect: true, musical: true, volume: 1 }) {
    if (!this.getData()) {
      console.log("StorageInfo初始化音乐配置");
      this.saveData(config);
    }
  }
  setAudio(config: AudioConfig_) {
    // console.log("StorageInfo储存的音乐配置：", config);
    this.saveData<AudioConfig_>(config);
  }
  get data() {
    return this.getData<AudioConfig_>();
  }
}


//////////////////////////////////////////
//-------------以下为类型限制接口--------//
/**游戏自残 */
export interface Fund_ {
  coin: number
  diamond: number
}
/**游戏房间配置 */
export interface GameRoomConfig {
  uid: number,
  roomid: number,
  score: number,
  roomtitle: string,
  base_score: string
}
/**游戏音效配置 */
export interface AudioConfig_ {
  soundEffect: boolean;
  musical: boolean;
  volume: number;
}
/**查询玩家信息接口 */
export interface QueryUserInfo {
  code: number;
  data: User;
  msg: string;
}

/**登录用户信息接口*/
export interface GamerInfoType {
  code: number;
  data: Data_;
  msg: string;
}

export interface Data_ {
  expires_at: number;
  token: string;
  user: User;
}
interface User {
  uid: number;
  CreatedAt: string;
  nickname: string;
  sex: number;
  avatarType: number;
  avatar: string;
  diamond: number;
  coin: number;
  ingot: number;
  point: number;
  vip: number;
  lastLoginTime: string;
  loginIp: string;
  matchNum: number;
  winCount: number;
  maxWinSreak: number;
  maxRecord: MaxRecord;
}
interface MaxRecord {
  spring: number;
  bomb: number;
  multiple: number;
  winCoin: number;
  title: number;
  duan: number;
}